<template>
    <div id="myMain">
        <div class="myMain-padding displayFlexC">
            <div class="tenAccountList-top main-top">
                <vxe-button icon="el-icon-delete" @click="delList">批量删除</vxe-button>
                <vxe-button icon="el-icon-plus" @click="details(null)">添加办公室</vxe-button>
                <vxe-button @click="importDataEvent" style="display:none"><i class="vxe-icon--upload"></i> 导入</vxe-button>
                <vxe-button @click="exportDataEvent"><i class="vxe-icon--download"></i> 导出</vxe-button>
            </div>
            <div class="tenAccountList-top">
                <span style="float:left;line-height:40px;margin-right:10px;">全表搜索：</span>
                <el-input v-model="searchVal" placeholder="" @input="searchEvents" prefix-icon="el-icon-search"></el-input>
            </div>
            <vxe-table
            ref="xTable"
            :filter-config="{showIcon: false}"
            border
            stripe
            highlight-hover-row
            :loading="loading"
            :data="tableData"
            :export-config="{}"
            @checkbox-all="selectAllEvent"
            @checkbox-change="selectChangeEvent"
            row-id="id"
            :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
            :checkbox-config="{reserve: true}">
            <vxe-table-column type="checkbox" width="60"></vxe-table-column>
            <vxe-table-column type="seq" title="序号" width="100"></vxe-table-column>
            <vxe-table-column field="contacts" title="联系人" width="130"></vxe-table-column>
            <vxe-table-column field="phone" title="联系方式" width="180"></vxe-table-column>
            <vxe-table-colgroup title="房源编号">
                <vxe-table-column field="houseNumber" :filters="[{data: ''}]" :filter-method="customStringFilterMethod" width="250">
                    <template #header="{ column }">
                        <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data" @change="filterEvent(option)" placeholder="请输入" clearable prefix-icon="el-icon-search"></vxe-input>
                    </template>
                </vxe-table-column>
            </vxe-table-colgroup>
            <vxe-table-colgroup title="区域">
                <vxe-table-column field="region" :filters="[{data: ''}]" :filter-method="customStringFilterMethod" width="250">
                    <template #header="{ column }">
                        <vxe-input type="text" v-for="(option, index) in column.filters" :key="index" v-model="option.data" @change="filterEvent(option)" placeholder="请输入" clearable prefix-icon="el-icon-search"></vxe-input>
                    </template>
                </vxe-table-column>
            </vxe-table-colgroup>
            <vxe-table-column field="lname" title="楼栋" width="100"></vxe-table-column>
            <vxe-table-column field="high" title="楼层" width="100"></vxe-table-column>
            <vxe-table-column field="unit" title="单元号" width="100"></vxe-table-column>
            <vxe-table-column field="area" title="面积" width="100"></vxe-table-column>
            <vxe-table-column field="aspect" title="朝向" width="100"></vxe-table-column>
            <vxe-table-column field="rentType" title="价格" width="100"></vxe-table-column>
            <vxe-table-column field="decorateType" title="装修情况" width="130">
                <template #default="{ row }">
                    <span v-if="row.decorateType == '未装修'">未装修</span>
                    <span v-else style="color:RGB(79,192,141);">已装修</span>
                </template>
            </vxe-table-column>
            <vxe-table-column field="elevator" title="是否有电梯" width="130">
                <template #default="{ row }">
                    <span v-if="row.elevator == '步梯房'">步梯房</span>
                    <span v-else style="color:RGB(79,192,141);">电梯房</span>
                </template>
            </vxe-table-column>
            <vxe-table-column field="rentStatus" title="房屋状态" width="130">
                <template #default="{ row }">
                    <span v-if="row.rentStatus == '未出租'" style="color:RGB(79,192,141);">未出租</span>
                    <span v-else>已出租</span>
                </template>
            </vxe-table-column>
             <vxe-table-column field="issueStatus" title="招商发布状态" width="130">
                <template #default="{ row }">
                    <span v-if="row.issueStatus == '已发布'" style="color:RGB(79,192,141);">已发布</span>
                    <span v-else>未发布</span>
                </template>
            </vxe-table-column>
            <vxe-table-column title="操作" width="150" fixed="right">
                <template #default="{ row }">
                    <vxe-button type="text" icon="el-icon-edit" title="修改" class="my_primary_btn" @click="details(row)"></vxe-button>
                    <vxe-button type="text" icon="el-icon-delete" title="删除" class="my_danger_btn" @click="removeEvent(row)"></vxe-button>
                </template>
            </vxe-table-column>
            </vxe-table>
            <!-- 分页 -->
            <vxe-pager
            perfect
            size="mini"
            :current-page="tablePage.currentPage"
            :page-size="tablePage.pageSize"
            :page-sizes="tablePage.pageSizes"
            :total="tablePage.totalResult"
            @page-change="pageChange"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total']">
            </vxe-pager>
        </div>
        <vxe-modal v-model="alertVal" title="添加房源" width="20%">
            <template #default>
                <vxe-form
                title-colon
                ref="xForm"
                title-align="right"
                title-width="130"
                :data="formData"
                :rules="formRules"
                @submit="submitEvent"
                @reset="resetEvent">
                <!-- <vxe-form-item title="房源编号" field="houseNumber" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.houseNumber" placeholder="请输入房源编号" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item> -->
                <!-- <vxe-form-item title="区域" field="region" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-select v-model="params.data.region" placeholder="请输入区域">
                            <vxe-option value="A区" label="A区"></vxe-option>
                            <vxe-option value="B区" label="B区"></vxe-option>
                            <vxe-option value="C区" label="C区"></vxe-option>
                        </vxe-select>
                    </template>
                </vxe-form-item> -->
                <vxe-form-item title="楼栋" field="buildId" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-select v-model="params.data.buildId" placeholder="请选择楼栋" :options="floors"></vxe-select>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="楼层" field="high" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.high" placeholder="请输入楼层" type="integer" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="单元号" field="unit" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.unit" placeholder="请输入单元号" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="面积" field="area" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.area" placeholder="请输入面积" type="integer" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="价格" field="rentType" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.rentType" placeholder="请输入价格" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="装修情况" field="decorateType" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <!-- <vxe-select v-model="params.data.decorateType" placeholder="请选择装修情况">
                            <vxe-option :value="1" label="已装修"></vxe-option>
                            <vxe-option :value="0" label="未装修"></vxe-option>
                        </vxe-select> -->
                        <vxe-select v-model="params.data.decorateType" placeholder="请选择装修情况" :options="decorateTypes"></vxe-select>
                    </template>
                </vxe-form-item>
                <!-- <vxe-form-item title="是否有电梯" field="elevator" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-select v-model="params.data.elevator" placeholder="请选择是否有电梯" :options="elevators"></vxe-select>
                    </template>
                </vxe-form-item> -->
                <!-- <vxe-form-item title="房屋状态" field="rentStatus" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-select v-model="params.data.rentStatus" placeholder="请选择房屋状态" :options="rentStatuss"></vxe-select>
                    </template>
                </vxe-form-item> -->
                <vxe-form-item title="联系人" field="contacts" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.contacts" placeholder="请输入联系人" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item title="联系方式" field="phone" span="24" :item-render="{}" title-overflow="title">
                    <template #default="params">
                        <vxe-input v-model="params.data.phone" placeholder="请输入联系方式" clearable @input="$refs.xForm.updateStatus(params)"></vxe-input>
                    </template>
                </vxe-form-item>
                <vxe-form-item align="center" :item-render="{}">
                    <template #default>
                    <vxe-button type="submit" status="primary">提交</vxe-button>
                    <vxe-button type="reset">重置</vxe-button>
                    </template>
                </vxe-form-item>
          </vxe-form>
            </template>
        </vxe-modal>
    </div>
</template>
<style lang="scss" scoped>
@import '../../../styles/all';
::v-deep.vxe-form .vxe-form--item:last-of-type{
  margin: 0 auto;
display: flow-root;
}
#myMain{
    .tenAccountList-top{
        margin-bottom: 20px;
        .vxe-button{
            margin-left: 10px;
        }
    }
}
</style>
<script>
import { getHouseInfo,addHouseInfo,delHouseInfoById,delHouseInfoByIdList,getBuildingInfo,putHouseInfofoById } from '@/api/parkManage'
import XEUtils from 'xe-utils'
export default {
    props: {
    },
    components:{},
    data(){
        const checkPhone = ({ itemValue}) => {
            if (!itemValue) {
                return new Error('请输入手机号码!')
            } else if (!(/^1[34578]\d{9}$/.test(itemValue))) {
                return new Error('请输入正确的手机号码!')
            } else {
                return false
            }
        }
        return{
            searchVal: '',
            loading: false,
            tableData: [],
            list: [
                { id: 10001, a: '123456', b: 'A区', c: 'A栋', d: '8层', e:'805', f:'150', g:'南', h:'未装修', i:'是', j:'未入住'},
                { id: 10001, a: '123457', b: 'B区', c: 'A栋', d: '9层', e:'910', f:'145', g:'南', h:'未装修', i:'是', j:'未入住'},
            ],
            // 分页
            tablePage: {
                currentPage: 1,
                pageSize: 10,
                pageSizes: [10, 20, 30, 40],
                totalResult: 0
            },
            // 弹窗
            alertVal: false,
            formData: {
                region: '',
                area: '',
                decorateType: '',
                high: '',
                buildId: '',
                // rentStatus: '0',
                unit: '',
                rentType: '',
                contacts: '',
                phone: ''
            },
            formRules: {
                region: [
                    { required: true, message: '请输入区域' }
                ],
                buildId: [
                    { required: true, message: '请输入楼栋' }
                ],
                high: [
                    { required: true, message: '请输入楼层' },
                    { min: 0, max: 100, type: 'number' , message: '请输入大于0的数值！'}
                ],
                unit: [
                    { required: true, message: '请输入单元号' },
                    { type: 'number' , message: '请输入数字！'}
                ],
                area: [
                    { required: true, message: '请输入面积' },
                    { min: 0, type: 'number' , message: '请输入大于0 的数字！'}
                ],
                decorateType: [
                    { required: true, message: '请输入装修情况' }
                ],
                rentType: [
                    { required: true, message: '请输入价格' }
                ],
                contacts: [
                    { required: true, message: '请输入联系人' }
                ],
                phone: [
                    { required: true, validator: checkPhone }
                ],
            },
            decorateTypes:[{
                label: '已装修',
                value: 1
            },{
                label: '未装修',
                value: 0
            }],
            elevators:[{
                label: '电梯房',
                value: 1
            },{
                label: '步梯房',
                value: 0
            }],
            rentStatuss:[{
                label: '已出租',
                value: 1
            },{
                label: '未出租',
                value: 0
            }],
            floors:[],
            checkBoxList: [],
            // 编辑还是添加
            addOrEdit: null,
        }
    },
    methods:{
        // 根据页切换
        pageChange(val){
            console.log('page val', val)
            this.tablePage.currentPage = val.currentPage
            let page = val.currentPage
            let limit = val.pageSize
            this.init(page, limit)
        },
        // 初始化
        async init(page, limit){
            await getBuildingInfo(page, limit).then(res => {
                let floorList = []
                console.log('楼栋 res', res)
                res.data.forEach( item => {
                    let obj = {}
                    obj['label'] = item.name
                    obj['value'] = item.id
                    floorList.push(obj)
                })
                this.floors = floorList
            })
            console.log('floors', this.floors)
            getHouseInfo(page, limit).then(res => {
                console.log('get res', res)
                this.list = res.data
                for(let i=0;i<this.list.length;i++){
                    if(this.list[i]['decorateType'] == 1){
                        this.list[i]['decorateType'] = '已装修'
                    }else{
                        this.list[i]['decorateType'] = '未装修'
                    }
                    if(this.list[i]['elevator'] == 1){
                        this.list[i]['elevator'] = '电梯房'
                    }else{
                        this.list[i]['elevator'] = '步梯房'
                    }
                    if(this.list[i]['rentStatus'] == 1){
                        this.list[i]['rentStatus'] = '已出租'
                    }else{
                        this.list[i]['rentStatus'] = '未出租'
                    }
                    if(this.list[i]['issueStatus'] == 1){
                        this.list[i]['issueStatus'] = '已发布'
                    }else{
                        this.list[i]['issueStatus'] = '未发布'
                    }
                    
                }
                this.list.forEach(item => this.floors.find(ele => 
                {
                    if(ele.label == item.lname){
                        item.buildId = ele.value
                    }
                }
                ))
                this.tablePage.totalResult = res.count
                this.tableData = this.list
            })
            // this.tablePage.totalResult = this.list.length
            // this.tableData = this.list.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
        },
        selectAllEvent ({ checked, records }) {
            this.checkBoxList = records
            // 全选
            console.log(checked ? '所有勾选事件' : '所有取消事件', records)
        },
        selectChangeEvent ({ checked, records }) {
            this.checkBoxList = records
            // 单选个
            console.log(checked ? '勾选事件' : '取消事件', records)
        },
        // 导出
        exportDataEvent () {
            this.$refs.xTable.openExport({
                // 默认勾选源
                original: true,
                types: ['csv']
            })
        },
        importDataEvent () {
            this.$message('楼栋请填写对应的楼栋ID，可以到“楼宇管理”查询对应的楼栋ID ！');
            // this.$refs.xTable.importData()
            // 获取导入的文件
            this.$refs.xTable.importData({ 
                types: ['csv'],
                remote: true,
                importMethod({ file, options }){
                    console.log('import file', file)
                }
            })
            // 读取导入文件数据
            // this.$refs.xTable.readFile({
            //     types: ['csv']
            //   }).then(params => {
            //     console.log('file params', params)
            //     const { files } = params
            //     const fileReader = new FileReader()
            //     fileReader.readAsText(files[0]);
            //     fileReader.onload = () => {
            //         let fileData = fileReader.result
            //         const resultData = []
            //         let headers = []
            //         fileData.split('\n').forEach((vRow, rIndex) => {
            //         if (vRow) {
            //           console.log('vRow', vRow)
            //           let vRowData = vRow.replace(/\r/g, '')
            //           let item = {}
            //           if(rIndex == 0){
            //               vRowData.split(',').forEach((vCols) => {
            //                 headers.push(vCols)
            //               })
            //           }else{
            //               vRowData.split(',').forEach((vCols, i) => {
            //                   // 去掉第一第二列（true ，id）
            //                   if(i>=2){
            //                       item[headers[i]] = vCols
            //                   }
            //               })
            //               resultData.push(item)
            //           }
                      
            //         }
            //       })
            //         console.log('导入的数据 resultData', resultData)
            //     }
            //   })
            
        },

        // 搜索
        searchEvents () {
            console.log(this.searchVal)
            const filterVal = XEUtils.toValueString(this.searchVal).trim().toLowerCase()
            const filterRE = new RegExp(filterVal, 'gi')
            const searchProps = ['aspect', 'area', 'high', 'unit', 'houseNumber', 'lname', 'region','issueStatus','decorateType','elevator','rentStatus']
            const rest = this.list.filter(item => searchProps.some(key => XEUtils.toValueString(item[key]).toLowerCase().indexOf(filterVal) > -1))
            this.tableData = rest.map(row => {
                const item = Object.assign({}, row)
                searchProps.forEach(key => {
                item[key] = XEUtils.toValueString(item[key]).replace(filterRE, match => `${match}`)
                })
                return item
            })
        },
        // 表内查找
        customStringFilterMethod ({ option, row, column }) {
            if (option.data) {
                return XEUtils.toValueString(row[column.property]).toLowerCase().indexOf((option.data).toLowerCase()) > -1
            }
            return true
        },
        filterEvent (option) {
            const xTable = this.$refs.xTable
            // 设置为选中状态
            option.checked = true
            // 修改条件之后，需要手动调用 updateData 处理表格数据
            xTable.updateData()
        },
        // 删除
        removeEvent (row) {
            this.$XModal.confirm('您确定要删除该数据?').then(type => {
                if (type === 'confirm') {
                    delHouseInfoById(row.id).then(res => {
                        console.log('res', res)
                        this.init(this.tablePage.currentPage, this.tablePage.pageSize)
                    })
                }
            })
        },
        // 删除多条
        delList(){
            let idList = []
            for (let i=0; i<this.checkBoxList.length; i++) {
                idList.push(this.checkBoxList[i].id)
            }
            // idList = JSON.stringify(idList)
            idList = idList.join(",")
            console.log('idList', idList)
            this.$XModal.confirm('您确定要删除该数据?').then(type => {
                if (type === 'confirm') {
                    delHouseInfoByIdList(idList).then(res => {
                        console.log('res delete', res)
                        this.init(this.tablePage.currentPage, this.tablePage.pageSize)
                    })
                }
            })
        },
        // 弹窗
        details(data){
            this.alertVal = true
            if (data != null) {
                this.addOrEdit = 1
                this.formData = data
            } else {
                this.addOrEdit = 0
                this.formData = {
                    // houseNumber: '',
                    region: '',
                    area: '',
                    // aspect: '',
                    decorateType: '',
                    // elevator: '',
                    high: '',
                    buildId: '',
                    // rentStatus: '0',
                    unit: '',
                    contacts: '',
                    phone: ''
                }
            }
        },
        async submitEvent(){
            console.log('this.formData', this.formData)
            if(this.addOrEdit ==0){
                // 新增
                const $form = this.$refs.xForm
                const errMap = await $form.validate().catch(errMap => errMap)
                if (errMap) {
                    this.$XModal.message({ status: 'error', message: '校验不通过！' })
                } else {
                    this.formData['rentStatus'] = 0
                    addHouseInfo(this.formData).then(res => {
                        console.log('add res', res)
                        if(res.resp_msg == '操作成功'){
                            this.alertVal = false
                            this.init(this.tablePage.currentPage,  this.tablePage.pageSize)
                        }
                    })
                    // this.$XModal.message({ status: 'success', message: '校验成功！' })
                }
            }else{
                // 修改
                //清除校验
                this.$refs.xForm.clearValidate()
                if(this.formData['decorateType'] == '已装修'){
                    this.formData['decorateType'] = 1
                }else{
                    this.formData['decorateType'] = 0
                }
                if(this.formData['elevator'] == '电梯房'){
                    this.formData['elevator'] = 1
                }else{
                    this.formData['elevator'] = 0
                }
                if(this.formData['rentStatus'] == '已出租'){
                    this.formData['rentStatus'] = 1
                }else{
                    this.formData['rentStatus'] = 0
                }
                putHouseInfofoById(this.formData).then(res => {
                    console.log('add res', res)
                    if(res.resp_msg == '操作成功'){
                        this.alertVal = false
                        this.init(this.tablePage.currentPage,  this.tablePage.pageSize)
                    }
                })
            }
            
        },
        resetEvent () {
            this.$XModal.message({ message: '重置表单内容!', status: 'info' })
        },
        
    },
    created(){},
    mounted(){
        this.init(this.tablePage.currentPage,  this.tablePage.pageSize)
    },
}
</script>